TARGET      := boot
BUILD_DIR   := build
SRC_DIR     := src
INC_DIR     := include
LINK_DIR    := link
# ======================
# ?????
# ======================
CROSS_COMPILE := arm-linux-gnueabihf-
CC          := $(CROSS_COMPILE)gcc
OBJCOPY     := $(CROSS_COMPILE)objcopy
LD          := $(CROSS_COMPILE)ld
SIZE        := $(CROSS_COMPILE)size
OBJDUMP		:= $(CROSS_COMPILE)objdump
CPU         := cortex-a7

# ======================
# ????
# ======================
CFLAGS      := -mcpu=$(CPU) -I$(INC_DIR) \
               -Wall -Wextra -g -Wl,--gc-sections \
			   -Wl,--wrap=malloc  -Wl,--wrap=free \
               -ffunction-sections -fdata-sections \
               -fno-common  -ffreestanding -fno-builtin-malloc \
			   -nostartfiles -static -marm
ASFLAGS     := -g
LDFLAGS     :=  -T $(LINK_DIR)/link.ld \
				-Wl,--gc-sections -nostartfiles  -static  -lc -Wl,--wrap=malloc \
				-marm		\
				-Wl,-Map=$(BUILD_DIR)/$(TARGET).map
DEPFLAGS    := -MMD -MP -MF $(BUILD_DIR)/$*.d

# ======================
# ????
# ======================
SRCS        := $(wildcard $(SRC_DIR)/*.c) $(wildcard $(SRC_DIR)/*.S)
OBJS        := $(patsubst $(SRC_DIR)/%,$(BUILD_DIR)/%,$(SRCS:.c=.o))
OBJS        := $(OBJS:.S=.o)
DEPS        := $(OBJS:.o=.d)

# ======================
# ????
# ======================
all: $(BUILD_DIR)/$(TARGET).bin size

$(BUILD_DIR)/$(TARGET).bin: $(BUILD_DIR)/$(TARGET).elf
	@echo "[OBJCOPY] $@"
	@$(OBJCOPY) -O binary $< $@

$(BUILD_DIR)/$(TARGET).elf: $(OBJS)
	@$(CC) $(LDFLAGS) $^ -o $@ -lc

$(BUILD_DIR)/%.o: $(SRC_DIR)/%.c | $(BUILD_DIR)
	@echo "[CC] $<"
	@$(CC) $(CFLAGS) $(DEPFLAGS) -c $< -o $@

$(BUILD_DIR)/%.o: $(SRC_DIR)/%.S | $(BUILD_DIR)
	@echo "[AS] $<"
	@$(CC) $(ASFLAGS) -c $< -o $@

# ??????
size: $(BUILD_DIR)/$(TARGET).elf
	@echo "[SIZE]"	
	$(OBJDUMP) -D build/boot.elf > boot.asm
	@$(SIZE) $<

# ??????
$(BUILD_DIR):
	@mkdir -p $@

# ??????
-include $(DEPS)

# ======================
# ????
# ======================
clean:
	@echo "[CLEAN]"
	@-rm -rf $(BUILD_DIR)

.PHONY: all clean size
